import os.path
#coding:utf-8
__author__ = "hzq"
__date__ = "$2011-7-25 17:52:20$"
import struct
import time

import Image
import cgi
import os
import random
import web
class upload:
    def __init__(self, dir, max=10, ext=()):
        self.backDir(dir)
        self.ext = ext
        cgi.maxlen = max * 1024 * 1024

    def backDir(self, dirs):
        tmp = time.strftime("/%Y/%m", time.localtime(time.time()))
    
        dirs = os.path.realpath(dirs + tmp)
        tmp = os.path.normpath(tmp)
        if os.path.isdir(dirs) == False:
            os.makedirs(dirs)
        self.dir = {"realdir":dirs, "dirname":tmp}

        
    def filename(self, data):
        '''检查文件类型
        严格  url 待检查
        '''
        filename = time.time() + random.randint(0, 10)
        typedict = {55551:"jpg", 20617:"png", 18759:"gif", 53200:"doc", 19280:"zip"}
        str = data[0:2]
        tmp = struct.unpack("H", str)
         

        if  typedict[tmp[0]] in self.ext:
            
            web.debug(typedict[tmp[0]])
        else:
            return False
           
            
       


        return  "%d.%s" % (filename, typedict[tmp[0]])
    def move(self, myfiles):
        x = web.input()
        sucess = []
        fails = []
        for myfile in myfiles:
            if (myfile in x)  and  len(x[myfile]) > 3:
                filename = self.filename(x[myfile])
                if filename:
                    fout = open(os.path.join(self.dir['realdir'], filename) , 'wb')
                    fout.write(x[myfile])
                    fout.close()
                    self.imgResize(os.path.join(self.dir['realdir'], filename),1000)
                    sucess.append(sucess.append(os.path.join(self.dir['dirname'], filename)))
                else:
                    fails.append('erro file type')
               
        
        
        return  {"fails":fails, "sucess":sucess}


    def imgResize(self, url, w=600):
        im = Image.open(url)
        (srcWidth,srcHeight)=im.size
        height = int(float(w)/float(srcWidth)*float(srcHeight))
        thumb=im.resize((w,height),Image.ANTIALIAS)
        thumb.save( url )
        
if __name__ == "__main__":
    u = upload("d:/c", 10, ('txt', 'jpg'))
